package com.kingner.config;

import com.kingner.utils.ACUtil;
import lombok.extern.java.Log;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;

@Configuration
@Slf4j
public class ACConfig {

    @Autowired
    private ACUtil acUtil;
    @Autowired
    private ResourcePatternResolver resolver;

    @Bean
    public ACUtil acUtil(){
        return new ACUtil();
    }


    @PostConstruct
    public void initAC() throws Exception {
        log.info("初始化AC自动机");
        String path = "classpath:sensitive_word/*";
        Resource[] resources = resolver.getResources(path);
        String line;
        for(Resource r: resources){
            File file = r.getFile();
            BufferedReader reader = new BufferedReader(new FileReader(file));
            while ((line = reader.readLine())!=null){
                if(!line.trim().isEmpty()){
                    acUtil.insert(line.trim());
                }
            }
        }
        acUtil.buildFailPoint();
    }
}
